import React from 'react'
import PropTypes from 'prop-types';
import { Cascader } from 'antd'
import { area } from './area'
import { city } from './city'
import { province } from './province'

/**
 * 根据省份，城市以及区域的数组，生成对应的选项
 * @param {*} regionArr (province|city|area)
 * @param {*} isArea 如果选择的是区域，则为三级联动的最后一级，设置isLeaf为true
 */
const setCascaderOption = (regionArr, isArea) => {
  let options = [];
  if (!regionArr || regionArr.length === 0) {
    return;
  }
  _.each(regionArr, (region) => {
    let option = {
      value: region.code,
      label: region.name,
      isLeaf: isArea
    };
    options.push(option);
  });
  return options;
};

let provinces = province;
let cities = city;
let areas = area;

class LwjArea extends React.Component {
  constructor(props) {
    super(props);
    // 数据源（默认为前端配置，如需使用后端的地区信息则设置为backEnd）
    this.dataSource = props.dataSource;
    if (this.dataSource === "backEnd" && (_.isEmpty(props.areaSummary) || _.isEmpty(props.citySummary) || _.isEmpty(props.provinceSummary))) {
      return;
    }
    // 判断数据来源
    if (!_.isEmpty(props.areaSummary) && !_.isEmpty(props.citySummary) && !_.isEmpty(props.provinceSummary)) {
      assembleRegionData();
    }
    // initial options
    let options = setCascaderOption(provinces, false);
    // initial state onChange由调用者传入
    this.onChange = props.onChange;
    // 默认值也由调用者提供 设置组件宽度
    this.width = props.width;
    // ES6 类中函数必须手动绑定
    this.loadData = this
      .loadData
      .bind(this);

    this.state = {
      options
    };

    /**
     * 组装后端传来的地区数据
     */
    function assembleRegionData() {
      provinces = props.provinceSummary;
      let cityObj = {};
      _.each(props.provinceSummary, (p) => {
        let cityOfProvince = _.filter(props.citySummary, (c) => {
          return c.provinceCode === p.code;
        });
        cityObj[p.code] = cityOfProvince;
      });
      cities = cityObj;

      let areaObj = {};
      _.each(props.citySummary, (c) => {
        let areaOfCity = _.filter(props.areaSummary, (a) => {
          return a.cityCode === c.code;
        });
        areaObj[c.code] = areaOfCity;
      });
      areas = areaObj;
    }
  }

  loadData = (selectedOptions) => {
    const targetOption = selectedOptions[selectedOptions.length - 1];
    const regionId = targetOption.value;
    targetOption.loading = true;
    if (selectedOptions.length === 1) {
      // 点击省,获取市
      targetOption.loading = false;
      let citiesInProvinces = [];
      // 根据省份ID获取该省份下的城市信息
      citiesInProvinces = cities[regionId];
      targetOption.children = setCascaderOption(citiesInProvinces, false);
      if (!targetOption.children || targetOption.children.length === 0) {
        targetOption.isLeaf = true;
      }
      this.setState({
        options: [...this.state.options]
      });
    } else if (selectedOptions.length === 2) {
      // 点击市,获取区域
      targetOption.loading = false;
      let areaInCity = [];
      // 根据城市ID获取该城市下的区域信息
      areaInCity = areas[regionId];
      targetOption.children = setCascaderOption(areaInCity, true);
      if (!targetOption.children || targetOption.children.length === 0) {
        targetOption.isLeaf = true;
      }
      this.setState({
        options: [...this.state.options]
      });
    } else {
      targetOption.loading = false;
    }
  }

  static getDerivedStateFromProps(props, state) {
    if (props.value) {
      let defaultProvince = props.value[0];
      let defaultCity = props.value[1];
      let targetProvince = state.options.filter(op => op.value === defaultProvince)[0];
      targetProvince = targetProvince || {}
      targetProvince.children = setCascaderOption(cities[defaultProvince], false) || [];
      let targetCity = {};
      if (!_.isEmpty(defaultCity)) {
        targetCity = targetProvince
          .children
          .filter(op => op.value === defaultCity)[0] || {};
        targetCity.children = setCascaderOption(areas[defaultCity], true);
      }
    }

    return {
      ...state,
      defaultValue: props.value,
      value: props.value
    }
  }

  render() {
    return (<Cascader
      defaultValue={this.state.defaultValue}
      options={this.state.options}
      loadData={this.loadData}
      onChange={this.onChange}
      placeholder="请选择省市区"
      changeOnSelect
      style={{
        width: this.width
      }}
    value={this.state.value}/>);
  }
}

LwjArea.propTypes = {
  onChange: PropTypes.func,
  dataSource: PropTypes.string,
  getProvinces: PropTypes.func,
  getCitiesByProvince: PropTypes.func,
  getAreaByCity: PropTypes.func
};

LwjArea.defaultProps = {
  width: 230
};

export default LwjArea
